import api from './index'

export interface OriginalDocument {
  id: number
  file_url: string
  cover_image_url: string
  is_parsed: string
  is_summarized: string
  file: string | null
  document_type: string
  knowledge_base_category: string
  file_name: string | null
  page_count: number | null
  cover_image: string | null
  parsing_status: string
  parsing_progress: number
  parsing_error: string | null
  visible: boolean
  summary_status: string
  created_at: string
  updated_at: string
}

// 获取知识库文档列表
export const getKnowledgeBaseDocuments = (): Promise<OriginalDocument[]> => {
  return api.get('/documents/?document_type=knowledge_base')
}

// 获取单个知识库文档
export const getKnowledgeBaseDocument = (id: number): Promise<OriginalDocument> => {
  return api.get(`/documents/${id}/`)
}

// 获取单个知识库文档详情
export const getKnowledgeBaseDocumentDetails = async (id: string): Promise<OriginalDocument> => {
  const response = await api.get(`/api/original-documents/${id}/`)
  return response.data
}

// 上传知识库文档
export const uploadKnowledgeBaseDocument = (
  file: File,
  documentType: string,
  knowledgeBaseCategory: string
): Promise<any> => {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('document_type', documentType)
  formData.append('knowledge_base_category', knowledgeBaseCategory)

  return api.post('/documents/', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
}

// 解析知识库文档
export const parseKnowledgeBaseDocument = (id: number): Promise<any> => {
  return api.post(`/parse-document/`, {
    document_id: id,
  })
}

// 删除知识库文档
export const deleteKnowledgeBaseDocument = (id: number): Promise<any> => {
  return api.delete(`/documents/${id}/`)
}

// 批量上传知识库文档
export const batchUploadKnowledgeBaseDocuments = (
  files: File[],
  knowledgeBaseCategory: string
): Promise<any> => {
  const formData = new FormData()
  files.forEach((file) => {
    formData.append('files', file)
  })
  formData.append('knowledge_base_category', knowledgeBaseCategory)

  return api.post('/batch-upload-documents/', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
}
